package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"shop/models"
)

type ShopController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	types := c.GetString("types")
	status := c.GetString("status")
	img := c.GetString("img")
	shop := models.Shop{
		Name:   name,
		Price:  price,
		Type:   types,
		Img:    img,
		Status: status,
	}
	err := models.DB.Debug().Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	page, _ := c.GetInt("page")
	size := 5
	var count int64
	models.DB.Model(&models.Shop{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	up := page - 1
	if up < 1 {
		up = 1
	}
	down := page + 1
	if down > sumpage {
		down = sumpage
	}
	var shop []models.Shop
	err := models.DB.Debug().Offset(offset).Limit(size).Find(&shop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		datapage := make(map[string]interface{})
		datapage["shop"] = shop
		datapage["up"] = up
		datapage["down"] = down
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: shop,
		}
		c.ServeJSON()
	}
}
